/**
 * Creates new Airpodder.util.Downloader
 * @constructor
 * @param {Object} config A config object
 */
Airpodder.util.Downloader = Ext.extend(Ext.util.Observable, {
  constructor: function(){
    Airpodder.util.Downloader.superclass.constructor.apply(this, arguments);

    this.addEvents(
      {"imageloaded" : true},
      {"fileloaded"  : true}
    );
    
    this.on('feedloaded', this.downloadImage);
  }

  /**
   * Закачка обложки подкаст-ленты
   */  
  , downloadImage: function (url, feed) {
    if (Ext.isEmpty(feed.image)) {
      return false;
    }
    var request   = new air.URLRequest(feed.image),
        stream    = new air.URLStream(),
        extension = feed.image.match(/(\.\w+)$/i);
        
    stream.addEventListener(air.Event.COMPLETE, 
                            this.saveImageOnDisk.createCallback(
                              this, 
                              stream, 
                              url, 
                              extension.length == 2 ? extension[1] : ''
                            ));
    stream.load(request);
  }
  
  /**
   * Сохранение обложки подкаст-ленты на диск
   */  
  , saveImageOnDisk: function (event, stream, url, extension) {
    var file_content = new air.ByteArray(),
        file_stream  = new air.FileStream(),
        channel      = Airpodder.data.channels.findChannel(url),
        file         = air.File.applicationStorageDirectory.resolvePath("images/" + channel.data.id + extension);

    stream.readBytes(file_content, 0, stream.bytesAvailable);
    file_stream.open(file, air.FileMode.WRITE);
    file_stream.writeBytes(file_content,0,file_content.length);
    file_stream.close();
    channel.set('image', channel.data.id + extension);
    channel.commit(true);
  }
  
  , downloadEpisode: function (id, url, filename) {
    if (Ext.isEmpty(id) || Ext.isEmpty(url) || Ext.isEmpty(filename)) {
      return false;
    }
    var grid      = Ext.getCmp('downloader_grid'),
        store     = grid.getStore();
    var grid_row  = store.getById(id);
    if (Ext.isEmpty(grid_row))
    {
      return false;
    }

    var file        = air.File.applicationStorageDirectory.resolvePath(filename),
        request     = new air.URLRequest(url),
        stream      = new air.URLStream(),
        file_stream = new air.FileStream();

    file_stream.openAsync(file, air.FileMode.WRITE);  
    stream.addEventListener(air.IOErrorEvent.IO_ERROR,  IOErrorDownloading);
    stream.addEventListener(air.ProgressEvent.PROGRESS, ProgressDownloading);  
    stream.addEventListener(air.Event.COMPLETE,         CompleteDownloading);  

    stream.load(request);
    grid_row.set('status', 'Downloading');
    grid_row.commit(true);
    
    function IOErrorDownloading(error) {
      c_log(error);
      grid_row.set('status', 'Error');
      grid_row.commit(true);
    }

    function ProgressDownloading(event) {  
      var file_content  = new air.ByteArray(),
          stream        = event.currentTarget,
          bytes_loaded  = event.bytesLoaded,
          bytes_total   = event.bytesTotal,
          total_percent = Math.round(bytes_loaded * 100 / bytes_total);
  
      if (total_percent != grid_row.get('progress')) {
        grid_row.set('progress', total_percent);
        grid_row.commit(true);
      }
      if (bytes_total != grid_row.get('size')) {
        grid_row.set('size',     bytes_total);
        grid_row.commit(true);
      }
        
      stream.readBytes(file_content, 0, stream.bytesAvailable);  
      file_stream.writeBytes(file_content, 0, file_content.length);  
     
      var progress_event = new air.ProgressEvent(air.ProgressEvent.PROGRESS);  
      progress_event.bytesLoaded = bytes_loaded;
      progress_event.bytesTotal  = bytes_total;
      air.NativeApplication.nativeApplication.dispatchEvent(progress_event);
    }
  
    function CompleteDownloading(event) {
      file_stream.close();
      stream.close();
  
      stream.removeEventListener(air.IOErrorEvent.IO_ERROR,  IOErrorDownloading);
      stream.removeEventListener(air.ProgressEvent.PROGRESS, ProgressDownloading);
      stream.removeEventListener(air.Event.COMPLETE,         CompleteDownloading);
  
      var event_complete = new air.Event(air.Event.COMPLETE);
      air.NativeApplication.nativeApplication.dispatchEvent(event_complete);
      grid_row.set('status', 'Complete');
      grid_row.commit(true);      
    }
  }
  
 

});
